<template>
  <div>
    <div>练习</div>
    <div ref="webgl"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  let scene: any = null;
  let camera: any = null;
  let render: any = null;
  let controls: OrbitControls;

  onMounted(() => {
    init();
  });
  function init() {
    scene = new THREE.Scene();

    // 正投影相机
    const width = window.innerWidth; //canvas画布宽度
    const height = window.innerHeight; //canvas画布高度

    camera = new THREE.PerspectiveCamera(90, width / height, 1, 1000);
    camera.position.set(300, 300, 300);
    camera.lookAt(scene.position);
    render = new THREE.WebGLRenderer();
    // 背景颜色
    render.setClearColor('#f1f2f6');
    render.setSize(width, height);
    webgl.value.appendChild(render.domElement);
    controls = new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);
    const pointLight = new THREE.PointLight(0xffffff);
    pointLight.position.set(100, 100, 100);
    scene.add(pointLight);
    const pointLightHelper = new THREE.PointLightHelper(pointLight);
    scene.add(pointLightHelper);

    const p1 = new THREE.Vector3(0, 0, 100);
    const p2 = new THREE.Vector3(0, 0, 30);
    const p3 = new THREE.Vector3(0, 10, 0);
    const p4 = new THREE.Vector3(30, 0, 0);
    const p5 = new THREE.Vector3(100, 0, 0);
    // 1. 3D直线线段
    const line1 = new THREE.LineCurve3(p1, p2);
    // 2. 三维二次贝塞尔曲线
    const curve = new THREE.QuadraticBezierCurve3(p2, p3, p4);
    // 3. 3D直线线段
    const line2 = new THREE.LineCurve3(p4, p5);

    const CurvePath = new THREE.CurvePath();
    // 三条线拼接为一条曲线
    CurvePath.curves.push(line1, curve, line2);

    // 执行.getPoints()，直线部分不会像曲线返回中间多余点，只需要起始点即可。
    // const pointsArr = CurvePath.getPoints(16) as THREE.Vector2[]; //曲线上获取点

    const geometry = new THREE.TubeGeometry(CurvePath as THREE.Curve<THREE.Vector3>, 50, 2, 25);
    const material = new THREE.LineBasicMaterial({
      color: 0xaa1100,
      side: THREE.DoubleSide,
    });
    const mesh = new THREE.Line(geometry, material);
    scene.add(mesh);
    renderFun();
  }

  function renderFun() {
    // 渲染循环

    controls.update(); //update()函数内会执行camera.lookAt(controls.target)
    render.render(scene, camera);
    requestAnimationFrame(renderFun);
  }
</script>
<style lang=""></style>
